import Vue from 'vue'
import Vuex from 'vuex'
import socket from '@/socket/index'

Vue.use(Vuex)

const state = {
  // 当前用户名称
  nickname: '',
  // 当前房间所有用户列表
  nicknames: null,
  // 当前房间主持人
  holder: '',
  // 保存绘图信息
  lines: [],
  // 标记连接,默认没连接
  connected: false,
  // 答案
  answer: '',
  // 启动游戏倒计时
  countDown: false,
  // 群聊所有信息
  rootTextAll: []
}

const mutations = {
  // 获取所有群聊
  updateRootText(state, roomALl) {
    state.rootTextAll = roomALl || []
  },
  // 添加新群聊的单条信息
  addRootText(state, currentItem) {
    state.rootTextAll.push(currentItem)
  },

  // 更新显示倒计时文本
  updateCountDown(state, flag) {
    state.countDown = flag
  },
  updateNickname(state, nickname) {
    state.nickname = nickname || ''
  },
  insertNicknames(state, nicknames) {
    state.nicknames = nicknames || null
  },
  updateHolder(state, holder) {
    state.holder = holder || ''
  },
  updateLines(state, lines) {
    state.lines = lines || []
  },
  updateConnected(state, flag) {
    state.connected = flag
  },
  // 用户猜中答案，积分+1
  addUserScore(state, nickname) {
    for (const key in state.nicknames) {
      if (key === nickname) {
        console.log(state.nicknames[key])
        state.nicknames[key].score += 1
      }
    }
  },

  // 保存新创建的线
  drawNewLine(state, line) {
    state.lines.push(line)
  },
  // 更新拖动的线
  updateLine(state, lastLine) {
    const line = state.lines[state.lines.length - 1]
    line.points = lastLine.points
  },
  // 清空画布
  clearLine(state) {
    state.lines = []
  },
  // 新玩家进入房间
  updateNickNames(state, userInfo) {
    const newNickNames = {}
    const { nickname } = userInfo
    for (const key in state.nicknames) {
      if (key === nickname) {
        newNickNames[key] = state.nicknames[key]
      } else {
        newNickNames[nickname] = userInfo
        newNickNames[key] = state.nicknames[key]
      }
    }
    state.nicknames = newNickNames
  },
  // 玩家退出游戏，删除用户信息
  delFromNicknames(state, nickname) {
    const obj = {}
    for (const key in state.nicknames) {
      if (key !== nickname) {
        obj[key] = state.nicknames[key]
      }
    }
    state.nicknames = obj
  },
  // 保存主持人答案
  saveAnswer(state, answer) {
    state.answer = answer
  }

}

const actions = {
  checkUserExist(context, nickname) {
    // 将socket异步返回的消息封装成promise
    return new Promise((resolve) => {
      // 发送消息称服务器对应的监听事件
      socket.emit('check_user_exist', nickname, isExist => {
        resolve(isExist)
      })
    })
  },
  // 向服务器发起申请，开始主持游戏
  sendStartGame(context, answer) {
    socket.emit('start_game', answer)
    context.commit('saveAnswer', answer)
  },
  // 向服务器校验答案正确性
  sendDanswerGame(context, answer) {
    socket.emit('answer_game', answer)
  },
  // 向服务器校验答案正确性
  sendStopGame(context) {
    socket.emit('stop_game', false)
  },
  // 将新创建的线同步到服务器中
  sendDrawLine(context, line) {
    socket.emit('new_line', line)
  },
  // 持续的更新当前的线条
  sendUpdateLine(context, lastLine) {
    socket.emit('update_line', lastLine)
  },
  // 离开游戏房间
  sendDropGame(context) {
    socket.emit('leave')
  },
  sendUserLeave(context) {
    socket.emit('leave')
    context.commit('updateNickname', '')
    localStorage.removeItem('nickname')
  },
  // 群聊用户发送消息:参数:发送的数据
  sendRoomText(context, { sendText, isText }) {
    const nickname = state.nickname
    const currentUserInfo = {}

    currentUserInfo['nickname'] = nickname
    currentUserInfo['profile'] = localStorage.getItem('profile') || ''
    currentUserInfo['info'] = sendText
    currentUserInfo['isText'] = isText
    context.commit('addRootText', currentUserInfo)
    socket.emit('room_text_add', currentUserInfo)
  },
  // 清空画布
  clearLine(context) {
    context.commit('clearLine')
    socket.emit('clear_line')
  }
}

const getters = {
  isGameStarted() {
    // 判断游戏是否开始-->通过判断是否有主持人
    return !!state.holder
  },
  getHolder() {
    return state.holder
  },
  // 判断是否为主持人
  checkHolder() {
    return state.nickname === state.holder
  },
  getUserLength() {
    return state.nicknames && Object.keys(state.nicknames).length
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
